package com.liebaut.controller.reports;

import com.liebaut.controller.CrudController;
import com.liebaut.dao.reports.ReportDetailsRepository;
import com.liebaut.dao.reports.ReportRepository;
import com.liebaut.exception.RestException;
import com.liebaut.model.reports.Report;
import com.liebaut.model.reports.ReportDetails;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.CrudRepository;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Controller
@RequestMapping("/report")
public class ReportController extends CrudController<Report, Long> {
    private static final Logger log = LoggerFactory.getLogger(ReportController.class);

    @Autowired
    private ReportDetailsRepository reportDetailsRepository;

    public ReportController() {
    }

    @Autowired
    public ReportController(ReportRepository repository) {
        super(repository);
    }

    @RequestMapping(value = "{id}/reportDetails", method = RequestMethod.POST, consumes = "application/json")
    @ResponseBody
    public Object addArticle(@PathVariable Long id, @RequestBody String body) throws IOException {
        try{
            ReportDetails details = new ObjectMapper().readValue(body, ReportDetails.class);
            Report report = repository.findOne(id);
            if(report != null){
                reportDetailsRepository.save(details);
                report.getReportDetails().add(details);
                repository.save(report);
                return details;
            } else
                throw new RestException(HttpStatus.NOT_FOUND, "ID not found: " + id);
        }  catch (JsonProcessingException e) {
            log.debug("invalid request", e);
            throw new HttpMessageNotReadableException("Invalid request", e);
        }
    }

    @Override
    public Iterable list(HttpServletRequest request) {
        String type = request.getParameter("type");
        if(type != null && type.length() > 0)
            return ((ReportRepository)repository).findByType(type);
        else
            return super.list(request);
    }
}
